package org.jsola.hr.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrPermissionConstants;
import org.jsola.hr.dto.CrmMemberAddDTO;
import org.jsola.hr.provider.IPermissionProviderService;
import org.jsola.hr.query.CrmMemberQuery;
import org.jsola.hr.service.ICrmMemberService;
import org.jsola.hr.vo.CrmMemberListVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * CRM 数据权限拦截器
 *
 * @author zdd
 */

@Component
@Slf4j
public class HrCrmJurisdictionInterceptorAdapter extends HandlerInterceptorAdapter {

    @Autowired
    private ICrmMemberService crmMemberService;

    @Autowired
    private IPermissionProviderService permissionProviderService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 获取下属成员列表
     */
    private static final String GET_CUSTOMER_PAGE = "/hr/api/v1/crmMembers";

    /**
     * 获取所有用户
     */
    private static final String GET_ALL_USER = "/hr/api/v1/crmMembers/getAllUser";

    /**
     * 用户修改权限
     */
    private static final String UPDATE_JURISDICTION = "/hr/api/v1/crmMembers/updateJurisdiction";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        TokenUser tokenUser = UserContext.getUser();
        String requestPath = request.getRequestURI();
        String[] pages = {GET_CUSTOMER_PAGE, GET_ALL_USER, UPDATE_JURISDICTION};
        List<String> pageList = Arrays.asList(pages);
        //获取当前用户权限
        CrmMemberQuery crmMemberQuery = new CrmMemberQuery();
        crmMemberQuery.setUserId(tokenUser.getUserId());
        int jurisdiction = 0;
        List<CrmMemberListVO> crmMemberListVOList = crmMemberService.select(crmMemberQuery, tokenUser.getSiteId());
        if (CollectionUtil.isEmpty(crmMemberListVOList)) {
            //当前用户是否超管
            if (permissionProviderService.isAdmin(tokenUser.getUserId(), tokenUser.getSiteId(), HrPermissionConstants.HR_DEFAULT_SUBJECT_ID, HrPermissionConstants.SYSTEM_SUBJECT_TYPE)) {
                //添加客户经理权限
                String lockKey = "addMember";
                RLock lock = redissonClient.getLock(lockKey);
                boolean hasLock;
                try {
                    // 加锁，等待0秒，上锁以后10秒自动解锁
                    hasLock = lock.tryLock(5, 60, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //锁内代码
                if(hasLock){
                    try {
                        List<CrmMemberListVO> crmMemberListVOList1 = crmMemberService.select(crmMemberQuery, tokenUser.getSiteId());
                        if (CollectionUtil.isEmpty(crmMemberListVOList1)) {
                            CrmMemberAddDTO crmMemberAddDTO = new CrmMemberAddDTO();
                            crmMemberAddDTO.setJurisdiction(1);
                            crmMemberAddDTO.setName(tokenUser.getUserName());
                            crmMemberAddDTO.setUserId(tokenUser.getUserId());
                            crmMemberService.save(crmMemberAddDTO, tokenUser);
                        }
                    } finally {
                        //释放锁
                        if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                            lock.unlock();
                        }
                    }
                }
                jurisdiction = 1;
            } else {
                log.info("用户不是超级管理员");
                throw new ParamException(("暂无操作权限"));
            }
        } else {
            jurisdiction = crmMemberListVOList.get(0).getJurisdiction();
        }
        if(jurisdiction == 0){
            log.info("用户权限jurisdiction为0");
            throw new ParamException(("暂无操作权限"));
        }
        if(jurisdiction == 2 && pageList.contains(requestPath)){
            log.info("用户权限jurisdiction为1不可方位"+requestPath+"接口");
            throw new ParamException(("暂无操作权限"));
        }
        return true;
    }
}